import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

/* 解决重复点击路由链接时控制台报错问题 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
	routes: [
		{
			path: '/',
			component: r => require(['../components/layout'], r),
			children: [
				{
					path: '',
					component: r => require(['../components/home'], r)
				},
				{
					path: '/door/list',
					component: r => require(['../components/door/list'], r)
				}
			]
		},
		{
			path: '/login',
			component: r => require(['../components/login'], r)
		},
		{
			path: '/404',
			component: r => require(['../components/404'], r)
		},
		{
			path: '*',
			redirect: '/404'
		}
	]
})

/* 访问前判断是否登录 */
router.beforeEach((to, from, next) => {
	if (to.path.startsWith('/login')) {
		sessionStorage.removeItem('token');
		next();
	} else {
		let token = sessionStorage.getItem('token');
		if (token) {
			next();
		} else {
			next({path: '/login'});
		}
	}
})

export default router
